package com.ztesoft.web.cleanup.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;

import com.ztesoft.core.spring.context.SpringApplicationContextHolder;
import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.Utils;
import com.ztesoft.web.baseconfig.db.po.DmPlanPO;
import com.ztesoft.web.common.DMSConstant;
import com.ztesoft.web.common.Util;
import com.ztesoft.web.common.customdb.dao.dto.DmTaskStageDto;
import com.ztesoft.web.common.vo.HostConnInfoVO;
import com.ztesoft.web.common.vo.HostConnMethodVO;
import com.ztesoft.web.common.vo.HostInfoPOJO;
import com.ztesoft.web.filecommon.customdb.dao.DmFCustomDao;
import com.ztesoft.web.filecommon.db.arg.DmFDetailArg;
import com.ztesoft.web.filecommon.db.dao.DmFDetailDao;
import com.ztesoft.web.filecommon.db.po.DmFDetailPO;
import com.ztesoft.web.filecommon.db.po.DmFPO;
import com.ztesoft.web.syncbaseinfo.service.BaseInfoService;
import com.ztesoft.web.syncbaseinfo.service.impl.BaseInfoServiceImpl;


public class CleanUpFileTask implements Callable<DmTaskStageDto> {
	
	private static final ZTEsoftLogManager logger = ZTEsoftLogManager.getLogger(CleanUpFileTask.class);

	private BaseInfoService baseInfoService;
	
	private DmTaskStageDto taskStagePO;
	
	private List<DmFPO> dmFPOList;
	
	private DmFDetailDao dmFDetailDao;
	
	private DmPlanPO planPO;
	
	private DmFCustomDao dmfCustomDao;
	
	public CleanUpFileTask(DmTaskStageDto taskStagePO,List<DmFPO> dmFPOList, DmPlanPO planPO) {
		this.taskStagePO = taskStagePO;
		this.dmFPOList = dmFPOList;
		this.planPO = planPO;
		baseInfoService = SpringApplicationContextHolder.getBean(BaseInfoServiceImpl.class);
		dmFDetailDao = SpringApplicationContextHolder.getBean(DmFDetailDao.class);
		dmfCustomDao =  SpringApplicationContextHolder.getBean(DmFCustomDao.class);
	}
	
	/* 
	 * //更新轨迹表执行中：：
	 * //遍历处理数据：：
	 * 		//执行RM：：
	 * 		//更新轨迹明细表：：
	 * 		//暂停 取消判断
	 * //更新轨迹表完成：：
	 */
	@Override
	public DmTaskStageDto call() {
		String checkState;
		int checkCount = 0;
		BigDecimal countSize = new BigDecimal(0);
		for (DmFPO dmFPO : dmFPOList) {
			loop : while(true) {
				try {
//					DmFDetailArg arg = new DmFDetailArg();
//					DmFDetailArg.DmFDetailCriteria criteria = arg.createCriteria();
//					criteria.andTrackIdEqualTo(dmFPO.getTrackId());
//					criteria.andDmTaskIdEqualTo(taskStagePO.getDmTaskId());
//					criteria.andStateEqualTo("00C");//待清理的数据
//					arg.setTableName("dm_f_detail_"+taskStagePO.getDmStrategyId());
//					arg.setLimit(1000);//限制1000条
//					List<DmFDetailPO> dmFDetailPOList = dmFDetailDao.selectByArg(arg);
					List<DmFDetailPO> dmFDetailPOList = dmfCustomDao.selectByTrackId(dmFPO.getTrackId(), taskStagePO.getDmStrategyId(),1000, "00C");
					logger.info("获取轨迹明细记录{0}",dmFDetailPOList.size());
					if (Utils.isEmpty(dmFDetailPOList)) {//若无数据，则退出改环节记录状态为00A state_date end_time
						taskStagePO.setState("00A");
						break loop;
					}
					
					HostConnInfoVO hostConnInfoVO = baseInfoService.getHostConn(dmFPO.getSrcIp());
					List<HostConnMethodVO> connMethods = hostConnInfoVO.getHostConnMethod();
					for (int i = 0, j = connMethods.size(); i < j; i++) {
						HostConnMethodVO methodVO = connMethods.get(i);
						if (dmFPO.getSrcUser().equals(methodVO.getUserName()) 
								&& DMSConstant.HOST_LINK_SSH.equals(methodVO.getConnMethod())) {
							//组装主机连接信息 HostInfoPOJO
							HostInfoPOJO hostInfoPOJO = 
									new HostInfoPOJO(hostConnInfoVO.getOsType(), hostConnInfoVO.getIp(), 
											methodVO.getUserName(), methodVO.getPassword(), methodVO.getPort(), true);
							rmFile(dmFDetailPOList, hostInfoPOJO);
							taskStagePO.setCheckCount(checkCount += dmFPO.getCheckDataCount());
							taskStagePO.setCheckDataSize(countSize.add(dmFPO.getCheckDataSize())); 
						}
					}
					checkState = baseInfoService.doCheck(taskStagePO, planPO);
					if (checkState != null) {
						taskStagePO.setCheckState(checkState);
						logger.info("暂停、取消处理{0}",checkState);
						return taskStagePO;
					}
				} catch (Exception e) {
					logger.error("clean up exception ...", e);
					taskStagePO.setErrorDesc(e.getCause().toString());
					taskStagePO.setCheckState(DMSConstant.FAIL);
					taskStagePO.setState("00F");
					dmfCustomDao.updateDetailStateByTrackId(taskStagePO.getDmStrategyId(), dmFPO.getTrackId(), "0CF");
					return taskStagePO;
				}
			}
		}
		taskStagePO.setCheckState(DMSConstant.SUCCESS);
		return taskStagePO;
	}

	private void rmFile(List<DmFDetailPO> dmFDetailPOList, HostInfoPOJO hostInfoPOJO) throws Exception{
		int j = dmFDetailPOList.size();
		String[] commands = new String[dmFDetailPOList.size()];
		for (int i = 0; i < j; i++) {
			commands[i] = "rm -rf " + dmFDetailPOList.get(i).getFilename();
			logger.info("清理命令集合{0}",commands[i]);
		}
		Util.execShellBySSHMethod(hostInfoPOJO, commands);
		Date stateDate = new Date();
		for (DmFDetailPO po : dmFDetailPOList) {
			po.setState("00A");
			po.setStateDate(stateDate);
			po.setTableName("dm_f_detail_"+taskStagePO.getDmStrategyId());
			dmFDetailDao.updateByPrimaryKeySelective(po);
		}

	}
	
}
